<?php


namespace app\service\common;


class WeatherService
{
    protected $url;
    protected $url1;
    public function __construct()
    {
        $this->url="http://d1.weather.com.cn";
        $this->url1="http://www.weather.com.cn";
    }

    /**
     * 获取天气的省份地区编码
     * @return \support\Response
     */
    public function getChinaProvince()
    {
        $time = bcdiv(time(), 1000);
        $url = $this->url1."/data/city3jdata/china.html?_=" . $time;
        return json_decode(http_get($url), true);
    }

    /**
     * 获取天气的城市地区编码
     * @param int $province_code
     * @return mixed
     */
    public function getChinaCity(int $province_code = 10127)
    {
        $time = bcdiv(time(), 1000);
        $url =  $this->url1."/data/city3jdata/provshi/{$province_code}.html?_=" . $time;
        return json_decode(http_get($url), true);
    }

    /**
     * 获取天气的地区编码
     * @param int $city_code
     * @return mixed
     */
    public function getChinaArea(int $city_code = 1012701)
    {
        $time = bcdiv(time(), 1000);
        $url =  $this->url1."/data/city3jdata/station/{$city_code}.html?_=" . $time;
        return json_decode(http_get($url), true);
    }

    /**
     * 获取全部的地区编码
     * @param string $city_name 城市名称,传递了就是当前城市的code值
     * @return array
     */
    public function city(string $city_name=""): array
    {
        $url="https://j.i8tq.com/weather2020/search/city.js";
        $data = json_decode(str_replace('var city_data = ','',http_get($url)),true);
        // 将多维数组转换为二维数组
        $list=[];
        foreach($data as $row){
            foreach($row as $val){
                foreach($val as $_val){
                    if ($city_name){
                        $c = $_val['NAMECN'];
                        if ($c==$city_name){
                            return $_val['AREAID'];
                        }
                    }else{
                        $list[]=$_val;
                    }
                }
            }
        }
        return $list;
    }


    /**
     * 获取地区的经纬度
     * @param string $city_code 城市的code值
     * @return array
     */
    public function getUrbanLongitudeAndLatitude(string $city_code="")
    {
        $time = bcdiv(time(), 1000);
        $url="http://i.tq121.com.cn/j/webgis_v2/city.json?callback=weacity&_=".$time;
        $get_data = http_get($url);
        $get_data = str_replace('weacity(','',$get_data);
        $get_data = str_replace(')','',$get_data);
        $data = json_decode($get_data,true);
        $all_data=[];
        if ($data){
            foreach ($data as $key=>$value){
                if ($city_code){
                    if ($city_code===$key){
                        return [
                            'code'=>$city_code,
                            'name'=>$value['n'],
                            'longitude'=>$value['x'],
                            'latitude'=>$value['y'],
                        ];
                    }
                }else{
                    $all_data[]=[
                        'code'=>$key,
                        'name'=>$value['n'],
                        'longitude'=>$value['x'],
                        'latitude'=>$value['y'],
                    ];
                }
            }
        }
        return $all_data;
    }

    public function getWeatherForecast($area_code=101270101): array
    {
        $time = bcdiv(time(), 1000);
        $url=$this->url."/dingzhi/{$area_code}.html?_=".$time;
        $data = str_replace('var cityDZ'.$area_code.' =','',http_get($url));
        $data_explode = explode(';var alarmDZ'.$area_code.' =',$data);
        return $data_arr = array_merge(json_decode($data_explode[0],true),json_decode($data_explode[1],true));
    }

    /**
     * 获取城市整点天气实况监测
     * @param int $area_code
     * @return mixed
     */
    public function getHours24(int $area_code=101270101)
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/aqi_all/{$area_code}.html?_=".$time;
        $data_strng = str_replace('setAirData(','',http_get($url));
        $data_strng = str_replace(')','',$data_strng);
        return json_decode($data_strng,true);
    }

    /**
     * 获取观测点的数据
     * @return mixed
     */
    public function getAirQuality()
    {
        $file_path_url=public_path('/weather/airQuality.js');
        $data = file_get_contents($file_path_url);
        $data_strng = str_replace('const setAirData = ','',$data);
        return json_decode($data_strng,true);
    }

    /**
     * 获取40天的天气
     * @param int $year
     * @param int $area_code
     * @param int $month
     * @return mixed
     */
    public function get40DayWeather(int $year=2023, int $area_code=101270101, int $month=202304)
    {
        $time = bcdiv(time(), 1000);
        $url=$this->url."/calendar_new/{$year}/{$area_code}_{$month}.html?_=".$time;
        return json_decode(str_replace('var fc40 = ','',http_get($url)),true);
    }
    /**
     * 获取15天的天气
     * @param int $area_code
     * @return mixed
     */
    public function get15DayWeather(int $area_code=101270101)
    {
        $time = bcdiv(time(), 1000);
        $url="http://www.weather.com.cn/weather15d/{$area_code}.shtml?_=".$time;
        $data = QueryList::get($url)
            ->rules([
                ['li>.time','texts'],
                ['li>.wea','texts'],
                ['li>.tem','texts'],
                ['li>.wind','texts'],
                //风级获取不到
                //['li>.wind1','texts']
            ])
            ->query()->getData()->toArray();
        $lists=[];
        for ($i=0;$i<count($data[0]);$i++){
            $lists[]=[
                'date'=>$data[0][$i],
                'condition'=>$data[1][$i],
                'temperature'=>$data[2][$i],
                'wind_direction'=>$data[3][$i],
            ];
        }
        return $lists;
    }
    /**
     * 获取今天的天气
     * @param int $area_code
     * @return mixed
     */
    public function getDayWeather(int $area_code=101270101)
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/sk_2d/{$area_code}.html?_=".$time;
        return json_decode(str_replace('var dataSK=','',http_get($url)),true);
    }


    /**
     * 获取近五天的天气情况
     * @param int $area_code
     * @return array
     */
    public function getWeatherIndex(int $area_code=101270101): array
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/weather_index/{$area_code}.html?_=".$time;
        $data_string =  str_replace('var cityDZ =','',http_get($url));
        $data_string = explode(';var alarmDZ =',$data_string);
        $data_string_two = explode(';var dataZS =',$data_string[1]);
        $data_string_three = explode(';var dataSK =',$data_string_two[0]);
        $data_string_four = explode(';var fc =',$data_string_two[1]);
        return array_merge(json_decode($data_string[0],true),json_decode($data_string_three[0],true),json_decode($data_string_three[1],true),json_decode($data_string_four[0],true),json_decode($data_string_four[1],true));
    }

    /**
     * 生活助手的数据
     * @param int $area_code
     * @return mixed
     */
    public function getLifeAssistant(int $area_code=101270101)
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/zs_index/{$area_code}.html?_=".$time;
        $data_string =  str_replace('var dataZS = ','',http_get($url));
        return $lists =json_decode($data_string,true);
    }

    /**
     * 获取地区的fc
     * @param int $area_code
     * @return mixed
     */
    public function getIndexFcHistory(int $area_code=101270101)
    {
        $year = date("Y");
        $month = date("Ym");
        $time = bcdiv(time(), 1000);
        $area_code=$area_code."_".$month;
        $url="http://d1.weather.com.cn/indexde/clothes_new/{$year}/{$area_code}.html?_=".$time;
        $data_string =  str_replace('var dataZS = ','',http_get($url));
        return $lists =json_decode($data_string,true);
    }

    /**
     * 获取景区和镇的天气地址
     * @param int $area_code
     * @return array
     */
    public function getAllScenicSpot(int $area_code=101270101): array
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/index_around_2017/{$area_code}.html?_=".$time;
        $data_string =  str_replace('var around=','',http_get($url));
        return $lists =json_decode($data_string,true);
    }


    /**
     * 获取天气类型,用户极端天气预警
     * @return array
     */
    public function getAllWeatherWarning(): array
    {
        $url="http://i.tq121.com.cn/j/data_alarm.js";
        $data_string =  str_replace('yjlb=','',http_get($url));
        $data_string =  str_replace('],gdlb=[',',',$data_string);
        $data_string =  str_replace('],yjyc=[',',',$data_string);
        $data_string =  str_replace('],$[',',',$data_string);
        $data_string =  str_replace('],$yjyc=[',',',$data_string);
        $data_string =  str_replace('],$gdyc=[',',',$data_string);
        $data_string =  str_replace('],gdyc=[',',',$data_string);
        $data_string =  str_replace('],$gdlb=[',',',$data_string);
        $data_array = explode(';var gradeObj=',$data_string);
        $data_array_two = explode(',kindObj=',$data_array[1]);
        $data_array_two0 = array_values(json_decode($data_array_two[0],true));
        $data_array_two1 =  str_replace(';','',$data_array_two[1]);
        $data_array_two_new = preg_replace('/\d+/', '"$0"', $data_array_two1);
        $data_array_two_new1 = str_replace('}"', '', $data_array_two_new);
        $data_array_two_new2 = str_replace('"{', '', $data_array_two_new1);
        $data_array_two_new4 = str_replace('""', '"', $data_array_two_new2);
        $data_array_two_new5 = str_replace('""', '"', $data_array_two_new4);
        $data_array_two110 = array_values(json_decode($data_array_two_new5,true));
        //$data_string =  str_replace('kindObj=',',',$data_string);
        $data =array_merge(json_decode($data_array[0]),$data_array_two0,$data_array_two110);
        return array_values(array_unique($data));
    }


    /**
     * 获取城市的生活指数
     */
    public function getLivingIndex($area_code=101270101)
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/zs_index/{$area_code}.html?_=".$time;
        $data_string =  str_replace('var dataZS=','',http_get($url));
        return json_decode($data_string,true);
    }

    /**
     * 日落和日出的信息
     * @param int $area_code
     * @return mixed
     */
    public function getForecast7Day(int $area_code=101270101)
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/forecast7d_jsp/{$area_code}.html?_=".$time;
        $data_string =  str_replace('var fc7d=','',http_get($url));
        return json_decode($data_string,true);
    }


    /**
     * 天气预警标题列表
     * @return mixed
     */
    public function getWeatherWarningInformation()
    {
        $time = bcdiv(time(), 1000);
        $url="http://product.weather.com.cn/alarm/grepalarm_cn.php?_=".$time;
        $data_string =  str_replace('var alarminfo=','',http_get($url));
        $data_string =  str_replace(';','',$data_string);
        return json_decode($data_string,true);
    }


    /**
     * 获取当前的预警信息
     * @param $warning_url
     * @return bool|string
     */
    public function getWeatherWarningContent($warning_url)
    {
        $time = bcdiv(time(), 1000);
        $url="http://product.weather.com.cn/alarm/webdata/{$warning_url}?_=".$time;
        return json_decode(str_replace('var alarminfo=','',http_get($url)),true);
    }

    /**
     * 预警等级信息和防御建议
     * @param string $warning_url
     * @return string|string[]
     */
    public function getWarningLevel(string $warning_url)
    {
        $string = str_replace('.html','',$warning_url);
        $array = explode('-',$string);
        $code = $array[2];
        $time = bcdiv(time(), 1000);
        $url="http://www.weather.com.cn/data/alarminfo/{$code}.html?_=".$time;
        return json_decode(str_replace('var alarmfyzn=','',http_get($url)),true);
    }

    /**
     * 获取预警全部的经纬度信息
     * @return mixed
     */
    public function getLatitudeLongitudeAll($warning_url)
    {
        $time = bcdiv(time(), 1000);
        $url="http://forecast.weather.com.cn/api/v1/traffic/alarm/alarmMap?callback=getAlarm&_=".$time;
        $data_strng = str_replace('getAlarm(','',http_get($url));
        $data_strng = str_replace(')','',$data_strng);
        $data = json_decode($data_strng,true);
        $data_content = $data['result']['data'];
        $coordinates ="";
        foreach ($data_content as $key=>$value){
            $warning_url_value = $value[1];
            if($warning_url_value == $warning_url){
                $coordinates = $value[6]['coordinates']??"";
            }
        }
        return $coordinates;
    }


    /**
     * 排行榜
     * @return string|string[]
     */
    public function getTodayRanking()
    {
        $time = bcdiv(time(), 1000);
        $url="https://d1.weather.com.cn/dataset/todayRanking.html?callback=todayRanking&_=".$time;
        $data_strng = str_replace('todayRanking(','',http_get($url));
        $data_strng = str_replace(')','',$data_strng);
        return json_decode($data_strng,true);
    }

    /**
     * 空气质量排行榜(前10)
     * @return mixed
     */
    public function getRankAQI()
    {
        $time = bcdiv(time(), 1000);
        $url="https://d1.weather.com.cn/aqi_paih/aqi_paih.html?callback=getRankAQI&_=".$time;
        $data_strng = str_replace('getRankAQI(','',http_get($url));
        $data_strng = str_replace(')','',$data_strng);
        return json_decode($data_strng,true);
    }

    /**
     * 获取全国省会城市的pm2.5
     * @return mixed
     */
    public function getPM25()
    {
        $time = bcdiv(time(), 1000);
        $url="http://d1.weather.com.cn/shaqi/shaqi.html?callback=shpm25&_=".$time;
        $data_strng = str_replace('shpm25(','',http_get($url));
        $data_strng = str_replace(')','',$data_strng);
        return json_decode($data_strng,true);
    }

}
